package com.amigo.online.provider.manager.mongo.dao.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;

import com.amigo.online.provider.manager.mongo.dao.UserDao;
import com.amigo.online.provider.manager.mongo.entity.Loc;
import com.amigo.online.provider.manager.mongo.entity.UserEntity;
import com.amigo.online.provider.manager.result.MerchantTblInfo;
import com.mongodb.BasicDBObject;
import com.mongodb.client.result.UpdateResult;

@Component
public class UserDaoImpl implements UserDao {

    @Autowired
    @Qualifier("mongoTemplate")
    private MongoTemplate mongoTemplate;

    @Autowired
    @Qualifier("merchantMongoTemplate")
    private MongoTemplate merchantMongoTemplate;

    @Override
    public void saveUser(UserEntity user) {
        mongoTemplate.save(user);
    }

    @Override
    public Long updateUser(UserEntity user) {
        Query query = new Query(Criteria.where("id").is(user.getId()));
        Update update = new Update().set("nickname", user.getNickname()).set("sex", user.getSex())
                .set("avatar", user.getAvatar()).set("birthday", user.getBirthday()).set("vip", user.getVip())
                .set("celebrity", user.getCelebrity()).set("verified", user.getVerified()).set("sign", user.getSign())
                .set("loginTime", user.getLoginTime()).set("platform", user.getPlatform()).set("loc", user.getLoc())
                .set("online", user.getOnline()).set("version", user.getVersion()).set("device", user.getDevice())
                .set("device", user.getDevice()).set("firstImg", user.getFirstImg()).set("openT", user.getOpenT())
                .set("checked", user.getChecked());
        UpdateResult result = mongoTemplate.updateFirst(query, update, UserEntity.class);
        if (result != null)
            return result.getModifiedCount();
        else
            return 0L;
    }

    @Override
    public void deleteUserById(Long id) {
        Query query = new Query(Criteria.where("id").is(id));
        mongoTemplate.remove(query, UserEntity.class);
    }

    @Override
    public UserEntity getUserById(Long id) {
        Query query = new Query(Criteria.where("id").is(id));
        return mongoTemplate.findOne(query, UserEntity.class);
    }

    @SuppressWarnings("deprecation")
    @Override
    public List<UserEntity> getLoginTimeUser(UserEntity user) {
        Query query = null;
        if (user.getId() != null && user.getId() > 0) {
            query = new Query(Criteria.where("loginTime").gt(System.currentTimeMillis() / 1000 - 86400).andOperator(Criteria.where("id").is(user.getId())));
        } else {
            query = new Query(Criteria.where("loginTime").gt(System.currentTimeMillis() / 1000 - 86400));
        }
        query.skip((user.getPageNo() - 1) * 10);
        query.limit(10);
        query.with(new Sort(new Order(Direction.DESC, "loginTime")));
        return mongoTemplate.find(query, UserEntity.class);
    }

    @Override
    public Integer getLoginTimeUserSize(UserEntity user) {
        Query query = null;
        if (user.getId() != null && user.getId() > 0) {
            query = new Query(Criteria.where("loginTime").gt(System.currentTimeMillis() / 1000 - 86400).andOperator(Criteria.where("id").is(user.getId())));
        } else {
            query = new Query(Criteria.where("loginTime").gt(System.currentTimeMillis() / 1000 - 86400));
        }
        return mongoTemplate.find(query, UserEntity.class).size();
    }

    @Override
    public Long updateMerchantLocation(MerchantTblInfo merchant) {
        Double[] point = new Double[2];
        point[0] = Double.valueOf(merchant.getMerchantTbl().getLng());
        point[1] = Double.valueOf(merchant.getMerchantTbl().getLat());
        Loc loc = new Loc();
        loc.setType("Point");
        loc.setCoordinates(point);
        BasicDBObject object = new BasicDBObject();
        object.append("type", "Point").append("coordinates", point);
        Query query = new Query(Criteria.where("_id").is(merchant.getMerchantTbl().getId()));
        Update update = new Update().set("_id", merchant.getMerchantTbl().getId())
                .set("user_id", merchant.getMerchantTbl().getUserId())
                .set("company_name", merchant.getMerchantTbl().getCompanyName())
                .set("merchant_name", merchant.getMerchantTbl().getMerchantName())
                .set("merchant_avatar", merchant.getMerchantTbl().getMerchantAvatar())
                .set("store_adderss", merchant.getMerchantTbl().getStoreAdderss())
                .set("category_id", merchant.getMerchantTbl().getCategoryId())
                .set("status", merchant.getMerchantTbl().getStatus())
                .set("deleted", merchant.getMerchantTbl().getDeleted())
                .set("loc", object)
                .set("_class", "com.amigo.online.provider.merchant.mongo.entity.merchantEntity");
        UpdateResult updateFirst = merchantMongoTemplate.upsert(query, update, "merchantEntity");
        return updateFirst.getModifiedCount();
    }

}
